package hse.jack.module;

import hse.jack.model.SysRole;
import hse.jack.model.SysRolePermission;
import hse.jack.util.DateUtil;
import hse.jack.util.DwzUtil;
import hse.jack.util.WebUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.service.EntityService;

/**
 * <b>角色操作action</b>
 * 
 * @author jack
 * @date 2013年1月7日15:41:03
 * @version 1.0
 * 
 */
@At("/role")
@IocBean(fields = { "dao" })
public class SysRoleModule extends EntityService<SysRole> {
	private static final Log log = Logs.get();

	/**
	 * 跳转到添加页面
	 */
	@At
	@Ok("jsp:page.role.roleInput")
	public void addUi() {

	}

	/**
	 * 跳转到修改页面
	 */
	@At
	@Ok("jsp:page.role.roleInput")
	public void editUi() {

	}

	/**
	 * 跳转到高级查询页面
	 */
	@At
	@Ok("jsp:page.role.query")
	public void queryUi() {

	}

	/**
	 * 跳转到授权页面
	 * 
	 * @param obj
	 * @return
	 */
	@At
	@Ok("jsp:page.role.permInput")
	public Object permUi(@Param("..") final SysRole obj) {
		try {
			Sql sql = Sqls
					.create("select wmsys.wm_concat(p.menu_id) menuids , p.role_id  from hse_sys_role_permission p "
							+ "where p.role_id = @roleID and not exists "
							+ "(select 1 from hse_sys_menu m where p.menu_id = m.parent_menu_id) group by p.role_id ");
			// Sql sql = Sqls
			// .create("select group_concat(p.menu_id) menuids , p.role_id  from hse_sys_role_permission p "
			// + "where p.role_id = @roleID and not exists "
			// +
			// "(select 1 from hse_sys_menu m where p.menu_id = m.parent_menu_id) group by p.role_id ");
			// 给赋值
			sql.params().set("roleID", obj.getRoleID());
			sql.setCallback(new SqlCallback() {
				@Override
				public Object invoke(Connection conn, ResultSet rs, Sql sql)
						throws SQLException {
					List<Map<String, Object>> menuMap = new ArrayList<Map<String, Object>>();
					if (rs.next()) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("menuIds", rs.getString("menuids"));
						map.put("roleId", rs.getString("role_id"));
						menuMap.add(map);
					} else {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("menuIds", "");
						map.put("roleId", obj.getRoleID());
						menuMap.add(map);
					}
					return menuMap;
				}
			});
			this.dao().execute(sql);
			return sql.getList(Map.class) == null ? "" : sql.getList(Map.class)
					.get(0);
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL, null, "菜单加载异常");
		}
	}

	/**
	 * 添加权限json對象 selecter
	 * 
	 * @return
	 */
	@At("/perm")
	@Ok("json")
	public Object permJson() {
		try {
			Sql sql = Sqls
					.create("select t.role_name text,t.role_id valueID from hse_sys_role t order by t.role_id");
			// 回调
			sql.setCallback(new SqlCallback() {
				@Override
				public Object invoke(Connection conn, ResultSet rs, Sql sql)
						throws SQLException {
					List<Map<String, String>> menuMap = new ArrayList<Map<String, String>>();
					while (rs.next()) {
						Map<String, String> map = new HashMap<String, String>();
						map.put("text", rs.getString(1));
						map.put("value", rs.getString(2));
						menuMap.add(map);
					}
					return menuMap;
				}
			});
			this.dao().execute(sql);
			return sql.getList(List.class);
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}
	}

	/**
	 * 授权方法
	 * 
	 * @param obj
	 * @param menuIds
	 * @return
	 */
	@At
	public Object addPerm(@Param("roleID") String roleID,
			@Param("menuIds") String menuIds) {
		try {
			this.dao().clear(SysRolePermission.class,
					Cnd.where("role_id", "=", roleID));
			if (menuIds != null && !"".equals(menuIds)
					&& !Strings.isEmpty(roleID)) {
				String[] menuId = menuIds.split(",");
				Sql sql = Sqls
						.create("insert into HSE_SYS_ROLE_PERMISSION(ROLE_ID,MENU_ID) VALUES(@roleID,@menuID)");
				for (int i = 0; i < menuId.length; ++i) {
					sql.params().set("roleID", roleID);
					sql.params().set("menuID",
							menuId[i] == null ? "" : menuId[i]);
					sql.addBatch();
				}
				// 持久化
				this.dao().execute(sql);
				return DwzUtil.dialogAjaxDone(DwzUtil.OK, "role");
			} else {
				return DwzUtil.dialogAjaxDone(DwzUtil.FAIL, null, "添加权限失败！");
			}
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}
	}

	/**
	 * 分页查询角色信息
	 * 
	 * @param pageNum
	 * @param numPerPage
	 * @param obj
	 * @return
	 */
	@At
	@Ok("jsp:page.role.roleList")
	public Object list(@Param("pageNum") int pageNum,
			@Param("numPerPage") int numPerPage, @Param("..") SysRole obj) {
		Pager pager = dao().createPager((pageNum < 1) ? 1 : pageNum,
				(numPerPage < 1) ? 20 : numPerPage);
		List<SysRole> list = dao().query(SysRole.class, bulidQureyCnd(obj),
				pager);
		Map<String, Object> map = new HashMap<String, Object>();
		if (pager != null) {
			pager.setRecordCount(dao().count(SysRole.class, bulidQureyCnd(obj)));
			map.put("pager", pager);
		}
		map.put("o", obj);
		map.put("list", list);
		return map;
	}

	/**
	 * 增加角色信息
	 * 
	 * @param obj
	 * @return
	 */
	@At
	public Object add(@Param("..") SysRole obj) {
		try {
			obj.setAddUserID(WebUtil.getLoginUser());
			obj.setAddTime(DateUtil.getCurrentDate());
			this.dao().insert(obj);
			return DwzUtil.dialogAjaxDone(DwzUtil.OK, "role");
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.debug("E!!", e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}

	}

	/**
	 * 更新角色信息
	 * 
	 * @param obj
	 * @return
	 */
	@At
	public Object update(@Param("..") SysRole obj) {
		try {
			obj.setAddUserID(WebUtil.getLoginUser());
			obj.setAddTime(DateUtil.getCurrentDate());
			this.dao().update(obj);
			return DwzUtil.dialogAjaxDone(DwzUtil.OK, "role");
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.debug("E!!", e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}
	}

	/***
	 * 删除角色信息
	 * 
	 * @param obj
	 * @return
	 */
	@At
	public Object delete(@Param("..") SysRole obj) {
		try {
			this.dao().delete(obj);
			return DwzUtil.dialogAjaxDone(DwzUtil.OK);
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.debug("E!!", e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}
	}

	/**
	 * 构建查询条件
	 * 
	 * @param obj
	 * @return
	 */
	private Cnd bulidQureyCnd(SysRole obj) {
		final String op = "=";
		Cnd cnd = null;
		if (null != obj) {
			cnd = Cnd.where("1", op, "1");
			/** 角色名称 **/
			if (!Strings.isEmpty(obj.getRoleName())) {
				cnd.and("role_name", op, obj.getRoleName());
			}
			/** 根据描述查询 **/
			if (!Strings.isEmpty(obj.getRoleDesc())) {
				cnd.and("role_desc", "like", "%" + obj.getRoleDesc() + "%");
			}
			/** 状态 **/
			if (!Strings.isEmpty(obj.getStatus())) {
				cnd.and("role_desc", op, obj.getStatus());
			}
		}
		return cnd;
	}
}
